import {
  Component,
  OnInit,
  OnDestroy,
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Inject,
  ViewChild,
  ElementRef,
} from '@angular/core';
import { _HttpClient, TitleService, SettingsService } from '@delon/theme';
import { NzNotificationService } from 'ng-zorro-antd';
import { STColumn } from '@delon/abc';
import { Subject } from 'rxjs';
import { ProductRefresh } from '../components/types';
import { BrandService, MSLayoutComponent, MSMenu } from '@brand';
import { ActivatedRoute, Router } from '@angular/router';
import { DOCUMENT } from '@angular/common';
import { RouteService } from '@core';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { saveAs } from 'file-saver';

/**
 * 产品资料页
 */
@Component({
  selector: 'app-product-view',
  templateUrl: './product-view.component.html',
  styleUrls: ['./product-view.component.less'],
})
export class ProductViewComponent implements OnInit, OnDestroy, AfterViewInit {
  param = '';
  current = 0;
  loading = false;
  product = null;
  extra = null;
  price = null;
  $refresh = new Subject<ProductRefresh>();
  @ViewChild('divinterest', { static: true }) interest: ElementRef;
  currentTpl: 'viewTpl' | 'saleTpl' | 'repairTpl' | 'testTpl' = 'viewTpl';

  prodinfo_export_btn = false;
  saledata_btn = false;
  repair_btn = false;

  btns = [
    { remark: '下载当前sku数据', icon: 'icon-download', loading: false },
    { remark: '下载同款数据', icon: 'icon-tongkuan', loading: false },
  ];
  tabs = [
    { icon: 'iconfont icon-jibenziliao', name: '产品详情' },
    { icon: 'iconfont icon-kucunliang', name: '库存' },
    { icon: 'iconfont icon-RectangleCopy', name: '价格' },
  ];
  navList: MSMenu[] = [];

  constructor(
    route: ActivatedRoute,
    public http: _HttpClient,
    private notice: NzNotificationService,
    private srv: BrandService,
    titSrv: TitleService,
    @Inject(DOCUMENT) private doc: any,
    private routeStateSrv: RouteService,
    private router: Router,
    private settings: SettingsService,
  ) {
    this.param = route.snapshot.params.productCd;
    titSrv.setTitle(`${this.param}产品详情`);
  }

  ngOnInit() {
    this.prodinfo_export_btn = this.settings.user.permissions.prodinfo_export_btn;
    this.saledata_btn = this.settings.user.permissions.saledata_btn;
    this.repair_btn = this.settings.user.permissions.repair_btn;

    this.navList = [
      {
        text: '基本信息',
        link: 'viewTpl',
      },
    ];
    if (this.saledata_btn) {
      this.navList.push({
        text: '销售数据',
        link: 'saleTpl',
      });
    }
    if (this.repair_btn) {
      this.navList.push({
        text: '售后统计',
        link: 'repairTpl',
      });
    }
    this.navList.push({
      text: '测试',
      link: 'testTpl',
    });

    this.loadProd();
  }

  ngAfterViewInit() {}

  ngOnDestroy(): void {
    this.$refresh.unsubscribe();
  }

  get isMobile() {
    return this.srv.isMobile;
  }

  selected(link) {
    this.currentTpl = link;
    const { product, price, extra } = this;
    this.$refresh.next({ product, price, extra });
  }

  /**
   * 加载商品信息
   */
  loadProd() {
    this.loading = true;
    this.http.get(`/cf/prod/sys-prod/view/${this.param}`).subscribe(res => {
      this.loading = false;
      if (res.status === 200) {
        this.product = res.data.product;
        this.extra = res.data.extra;
        this.price = res.data.price;
        const { product, price, extra } = this;
        this.$refresh.next({ product, price, extra });
      }
    });
  }

  changeTab(e) {
    this.current = e.index;
  }

  toggleInterest() {
    if (this.interest) {
      const _el = this.interest.nativeElement;
      if (_el.classList.contains('interest-active')) {
        _el.classList.remove('interest-active');
      } else {
        _el.classList.add('interest-active');
      }
    }
  }

  back() {
    this.router.navigateByUrl(`/prod/list`, {
      state: {
        pi: this.routeStateSrv.pi,
        q: this.routeStateSrv.get('q'),
        expandMode: this.routeStateSrv.get('expandMode'),
      },
    });
  }

  toggle() {
    this.srv.hideNav = !this.srv.hideNav;
    this.srv.triggerNotify('page-nav');
  }
  get hideNav() {
    return this.srv.hideNav;
  }

  downloadFile(idx) {
    this.btns[idx].loading = true;
    const head = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    });
    this.http
      .request(
        'get',
        `/cf/prod/sys-prod/export?type=${idx === 0 ? 'SKU' : 'STYLE'}&keyword=${
          idx === 0 ? this.product.productCd : this.product.style
        }`,
        {
          headers: head,
          responseType: 'blob',
          observe: 'response',
          params: {},
        },
      )
      .subscribe((res: HttpResponse<Blob>) => {
        this.btns[idx].loading = false;
        const filename = `${idx === 0 ? this.product.productCd : this.product.style}.xlsx`;
        saveAs(res.body, decodeURI(filename));
      });
  }
}
